#include "gx_lock.h"
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>

int reg_lock(int fd,int cmd,short type,short whence,off_t start,off_t len)
{
	struct flock lock;
	lock.l_type = type;
	lock.l_whence = whence;
	lock.l_start = start;
	lock.l_len = len;
	return (fcntl(fd,cmd,&lock));
}

int test_lock(int fd,short type,short whence,off_t start,off_t len)
{
	struct flock lock;
	lock.l_type = type;
	lock.l_whence = whence;
	lock.l_start = start;
	lock.l_len = len;

	if(fcntl(fd,F_GETLK,&lock) != 0)
	{
		perror("fcntl");
		exit(1);
	}

	if(lock.l_type == F_UNLCK)
	{
		return 0;
	}
	else
	{
		return lock.l_pid;
	}
}

void lockfile(char* name)
{
	char filename[256] = {0};
	struct flock lock;
	snprintf(filename,sizeof(filename),"/var/run/%s.pid",name);
	int fd = open(filename,O_RDWR|O_CREAT,0700);

	lock.l_type = F_WRLCK;
	lock.l_whence = SEEK_SET;
	lock.l_start = 0;
	lock.l_len = 0;

	if(fcntl(fd,F_SETLK,&lock)<0)
	{
		printf("%s running\n",name);
		exit(1);
	}
	else
	{
		char pid[20]={0};
		snprintf(pid,sizeof(pid),"%d",getpid());
		write(fd,pid,strlen(pid));
	}
}
